const connect = require("connect");
const http = require("http");
const serveStaticMiddleware = require("./middlewares/static");
const resolveConfig = require("../config");
const { createOptimizeDepsRun } = require("../optimizer");

const transformMiddleware = require("./middlewares/transfrom");
const { createPluginContainer } = require("./pluginContainer");

async function createServer() {
  const middlewares = connect();
  const config = await resolveConfig();

  const pluginContainer = await createPluginContainer(config);

  const server = {
    pluginContainer,
    async listen(port) {
      // 解析第三方库的引入路径
      await runOptimize(config, server);

      http.createServer(middlewares).listen(port, () => {
        console.log(`Server running at http://localhost:${port}`);
      });
    },
  };

  // 转换第三方库的引入路径 import {createApp} from 'vue' => import {createApp} freom '/node_modules/.vite/deps/vue.js'
  middlewares.use(transformMiddleware(server));
  // 注册静态文件中间件
  middlewares.use(serveStaticMiddleware(config));

  return server;
}

async function runOptimize(config, server) {
  const optimizeDeps = await createOptimizeDepsRun(config);
  server._optimizeDepsMetadata = optimizeDeps.metadata;
}

module.exports = {
  createServer,
};
